package com.jilefojing.session.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jilefojing.beans.constant.Constants;
import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.enums.ServerTypeEnum;
import com.jilefojing.beans.enums.foruser.StatusEnumForUser;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.User;
import com.jilefojing.beans.pojos.enhanced.EnhancedUser;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.IUserService;
import com.jilefojing.session.service.IUserContextService;
import com.jilefojing.util.Detect;
import com.jilefojing.util.MD5Util;
import com.jilefojing.util.QiniuUtil;

/**
 * 用户上下文服务
 * 
 * @author jgshun
 * 
 */
@Service
public class UserContextService implements IUserContextService {
	// TODO 待办
	@Autowired(required = false)
	private HttpSession session;
	// TODO 待办
	@Autowired(required = false)
	private HttpServletRequest request;
	@Autowired
	private IUserService userService;

	private static final String SCHEMA = "http";

	@Override
	public UserContext getDefaultUserContext() {
		UserContext userContext = (UserContext) session
				.getAttribute(Constants.USER_CONTEXT_KEY);
		if (userContext != null) {
			this.updateOperator(userContext);
		}
		return userContext;
	}

	@Override
	public UserContext loadUserContext(String account, String password,
			ServerTypeEnum typeEnum) throws UserContextException {
		return this.loadUserContextWithEncryptPassword(account,
				MD5Util.getMD5Str(password), typeEnum);
	}

	@Override
	public UserContext loadUserContextWithEncryptPassword(String account,
			String encryptPassword, ServerTypeEnum typeEnum)
			throws UserContextException {
		UserContext userContext = this.loadUserContext(account,
				encryptPassword, true, typeEnum);
		return userContext;
	}

	@Override
	public UserContext loadUserContextWithoutPassword(String account,
			ServerTypeEnum typeEnum) throws UserContextException {
		UserContext userContext = this.loadUserContext(account, null, false,
				typeEnum);
		return userContext;
	}

	@Override
	public UserContext loadUserContext(long id, ServerTypeEnum serverType)
			throws UserContextException {
		if (!serverType.isjilefojingServer()) {
			throw new UserContextException("非法操作:[仅支持jilefojingServer]");
		}

		EnhancedUser enhancedUser = userService.getEnhancedUser(id);

		if (enhancedUser == null) {
			throw new UserContextException(ResponseEnum.USER_NOT_EXIST);
		}

		if (Detect.notEmpty(enhancedUser.getPortraitUrl())
				&& !enhancedUser.getPortraitUrl().toLowerCase()
						.startsWith(SCHEMA)) {
			enhancedUser.setPortraitUrl(QiniuUtil.getImagesDomain()
					+ enhancedUser.getPortraitUrl());
		}

		UserContext userContext = new UserContext();
		userContext.setEnhancedUser(enhancedUser);

		userContext.setServerType(serverType);
		this.updateOperator(userContext);
		// TODO 待办
		// session.setAttribute(Constants.USER_CONTEXT_KEY, userContext);

		return userContext;
	}

	/**
	 * 加载用户上下文
	 * 
	 * @param account
	 *            账户
	 * @param encryptPassword
	 *            密文密码
	 * @param isNeedPasswrod
	 *            是否需要密码
	 * @param serverType
	 *            服务程序类型
	 * @return
	 * @throws UserContextException
	 */
	private UserContext loadUserContext(String account, String encryptPassword,
			boolean isNeedPasswrod, ServerTypeEnum serverType)
			throws UserContextException {
		UserContext userContext = null;
		if (serverType.isjilefojingServer()) {
			userContext = this.loadjilefojingServerUserContext(account,
					encryptPassword, isNeedPasswrod);
		} else {
			// TODO
		}

		userContext.setServerType(serverType);
		this.updateOperator(userContext);
		// TODO 待办
		// session.setAttribute(Constants.USER_CONTEXT_KEY, userContext);
		return userContext;
	}

	/**
	 * 加载通用程序用户的上下文
	 * 
	 * @param account
	 * @param encryptPassword
	 * @param isNeedPasswrod
	 * @return
	 * @throws UserContextException
	 */
	private final UserContext loadjilefojingServerUserContext(String account,
			String encryptPassword, boolean isNeedPasswrod)
			throws UserContextException {
		User user = userService.getUserByAccount(account);

		if (user == null) {
			throw new UserContextException(ResponseEnum.USER_NOT_EXIST);
		}
		if (isNeedPasswrod) {
			if (!user.getPassword().equals(encryptPassword)) {
				throw new UserContextException(ResponseEnum.PASSWORD_ERROR);
			}
		}
		UserContext userContext = new UserContext();
		userContext.setEnhancedUser(new EnhancedUser(user));
		return userContext;
	}

	@Override
	public void removeUserContext(UserContext userContext)
			throws UserContextException {
		session.removeAttribute(Constants.USER_CONTEXT_KEY);
	}

	/**
	 * 更新操作
	 * 
	 * @param userContext
	 */
	private final void updateOperator(UserContext userContext) {
		// TODO 待办
		// String uri = request.getRequestURI();
		// if (Detect.notEmpty(uri)) {
		// uri = uri.substring(uri.indexOf("/", 1));
		// userContext.setOperator(uri);
		// userContext.setOperatorDate(new Date());
		// }
	}

	@Override
	public boolean checkUserContext(UserContext userContext)
			throws UserContextException {
		if (userContext == null) {
			throw new UserContextException("UserContext不能为null");
		}
		if (userContext.getServerType().isjilefojingServer()) {
			if (userContext.getUserId() < 1
					&& (userContext.getEnhancedUser() == null || userContext
							.getEnhancedUser().getId() < 1)) {
				throw new UserContextException("[用户id有误("
						+ userContext.getUserId() + ")]");
			}
			long id = userContext.getUserId() < 1 ? userContext
					.getEnhancedUser().getId() : userContext.getUserId();

			User user = userService.getById(id, null);
			if (user == null) {
				throw new UserContextException(ResponseEnum.USER_NOT_EXIST);
			}
			StatusEnumForUser status = StatusEnumForUser
					.getStatusEnumByCode(Short.valueOf(String.valueOf(user
							.getStatus())));
			if (status == null || status == StatusEnumForUser.INVALID) {
				throw new UserContextException(ResponseEnum.USER_INVALID);
			}
			userContext.setEnhancedUser(new EnhancedUser(user));
		} else {
			// TODO
		}

		return true;
	}

	@Override
	public void isjilefojingServer(UserContext userContext)
			throws UserContextException {
		if (!userContext.getServerType().isjilefojingManagerServer()) {
			throw new UserContextException("[仅为jilefojing_MANAGER提供]");
		}
	}

}
